<template>
  <div class="app-container">
    <div class="button_warp">
      <el-button @click="toCreate">+ 创建</el-button>
    </div>
    <el-table
      v-loading="loading"
      ref="multipleTable"
      :data="tableData"
      tooltip-effect="dark"
      style="width: 100%"
      border
    >
      <!-- 表单数据 -->
      <el-table-column width="60" prop="id" label="ID" max-height="50" />
      <el-table-column prop="name" label="角色名称" />
      <el-table-column prop="status" label="状态" />
      <el-table-column prop="create_time" label="创建时间" />
      <el-table-column prop="update_time" label="更新时间"/>
      <!-- 操作 -->
      <el-table-column label="操作" width="225">
        <template slot-scope="scope">
          <el-button size="mini" @click="toEdit(scope.row.id)">编辑</el-button>
          <el-button size="mini" style="margin-left: 0px;" @click="toRole(scope.row.id)">权限</el-button>
          <el-button size="mini" type="danger" style="margin-left: 0px;" @click="toDelete(scope.row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-dialog :title="titleName" :visible.sync="addFormVisible">
      <el-form ref="addForm" :model="addForm" :rules="addFormRules" label-width="100px">
        <el-form-item label="角色名称" prop="name">
          <el-input v-model="addForm.name" auto-complete="off"/>
        </el-form-item>
        <el-form-item label="状态：">
          <el-radio v-model="addForm.flag" label="1">启用</el-radio>
          <el-radio v-model="addForm.flag" label="2">禁用</el-radio>
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button @click.native="addFormVisible = false">取消</el-button>
        <el-button type="primary" @click.native="addSubmit">提交</el-button>
      </div>
    </el-dialog>

    <el-dialog :visible.sync="menuVisible">
      <el-tree
        ref="tree"
        :data="menuData"
        :props="defaultProps"
        show-checkbox
        default-expand-all
        node-key="id"
        highlight-current
        class="filter-tree"/>
      <div slot="footer" class="dialog-footer">
        <el-button @click.native="menuVisible = false">取消</el-button>
        <el-button type="primary" @click.native="roleSubmit">提交</el-button>
      </div>
    </el-dialog>

    <!-- 分页 -->
    <div class="block myPaginate">
      <el-pagination
        :current-page="currentPage"
        :page-sizes="[10, 20, 30, 40, 50]"
        :page-size="pageSize"
        :total="dataTotal"
        layout="total, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
  </div>
</template>

<script>
import { roleList, roleCreate, roleEdit, roleDetail, roleDelete, getMenu } from '../../../api/admin'
export default {
  data() {
    return {
      tableData: [],
      menuData: [],
      defaultProps: {
        children: 'children',
        label: 'name'
      },
      role_id: 0,
      addForm: {
        add: true,
        name: '',
        flag: '1'
      },
      titleName: '新增',
      addFormRules: {
        name: [
          { required: true, message: '请输入帐号名', trigger: 'blur' }
        ]
      },
      addFormVisible: false,
      menuVisible: false,
      currentPage: 1, // 当前页
      dataTotal: 0, // 数据总数
      pageSize: 20,
      loading: true
    }
  },
  mounted() {
    this.getData()
  },
  methods: {
    getData() {
      const params = {
        page: this.currentPage,
        limit: this.pageSize
      }
      roleList(params).then(data => {
        console.log(data)
        this.loading = false
        if (data.code === 0) {
          this.tableData = data.data.list
          this.dataTotal = data.data.count
        } else {
          this.$message({
            showClose: true,
            message: data.msg,
            type: 'error'
          })
        }
      })
    },
    // 新增、修改操作
    addSubmit() {
      this.$refs.addForm.validate((valid) => {
        if (valid) {
          if (this.addForm.add) {
            this.addForm.role_id = this.role_id
            const para = Object.assign({}, this.addForm)
            roleCreate(para).then(data => {
              if (data.code === 0) {
                this.$message({
                  message: '创建成功',
                  type: 'success'
                })
                this.$refs['addForm'].resetFields()
                this.addFormVisible = false
                this.getData()
              }
            })
          } else {
            const para = Object.assign({}, this.addForm)
            roleEdit(para).then(data => {
              // this.addLoading = false;
              if (data.code === 0) {
                this.$message({
                  message: '保存成功',
                  type: 'success'
                })
                this.$refs['addForm'].resetFields()
                this.addFormVisible = false
                this.getData()
              }
            })
          }
        }
      })
    },
    // 创建
    toCreate() {
      this.addFormVisible = true
      this.addForm.add = true
      this.titleName = '新增'
    },
    // 修改
    toEdit(id) {
      roleDetail({ id: id }).then(data => {
        if (data.code === 0) {
          this.addForm = data.data
        }
      })
      this.titleName = '编辑'
      this.addFormVisible = true
      this.addForm.add = false
    },
    // 权限
    toRole(id) {
      this.role_id = id
      // 获取菜单
      getMenu({ id: id }).then(data => {
        if (data.code === 0) {
          this.menuVisible = true
          this.menuData = data.data.menus
          // 设置菜单选中
          this.$nextTick(() => {
            data.data.auth_ids.map((i, n) => {
              // 根据i获取tree中的节点
              var node = this.$refs.tree.getNode(parseInt(i))
              if (node.isLeaf) {
                // 设置某个节点的勾选状态
                this.$refs.tree.setChecked(node, true)
              }
            })
          })
        }
      })
    },
    toDelete(id) {
      this.$confirm('此操作将永久删除, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        roleDelete({ id: id }).then(data => {
          if (data.code === 0) {
            this.getData()
            this.$message({
              showClose: true,
              message: data.data,
              type: 'success'
            })
          }
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    // 权限编辑提交
    roleSubmit() {
      const ids = [...this.$refs.tree.getHalfCheckedKeys(), ...this.$refs.tree.getCheckedKeys()].join(',')
      console.log(ids)
      roleEdit({ id: this.role_id, auth_ids: ids }).then(data => {
        console.log(data)
        if (data.code === 0) {
          this.menuVisible = false
          this.$message({
            showClose: true,
            message: data.data,
            type: 'success'
          })
        }
      })
    },
    // 分页事件
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`)
    },
    handleCurrentChange(val) {
      this.currentPage = val
      this.getData()
    }
  }
}
</script>
